﻿namespace Blaze.Editor
{
    using System;
    using System.Reflection;
    using UnityEditor;
    using UnityEditor.Rendering;
    using UnityEngine;
    using UnityEngine.Rendering;
    using Object = UnityEngine.Object;

    /// <summary>
    /// <see cref="EditorGraphicsSettings"/>扩展。
    /// </summary>
    public static class GraphicsSettingsExtension
    {
        /// <summary>
        /// 获取所有总是包含到包内的<see cref="Shader"/>资源。
        /// </summary>
        /// <returns></returns>
        public static Shader[] GetAlwaysIncludedShaders()
        {
            return AlwaysIncludedShaders.ReadArray<Shader>();
        }

        /// <summary>
        /// 设置总是包含到包内的<see cref="Shader"/>资源。
        /// </summary>
        public static void SetAlwaysIncludedShaders(Shader[] shaders)
        {
            AlwaysIncludedShaders.WriteArray(shaders);
            AlwaysIncludedShaders.serializedObject.ApplyModifiedProperties();
        }

        private static Editor mAlwaysIncludedShadersEditor;
        private static readonly Type mAlwaysIncludedShadersEditorType = Assembly.GetAssembly(typeof (Editor)).GetType("UnityEditor.GraphicsSettingsWindow.AlwaysIncludedShadersEditor");

        #region reflected properties

        private static SerializedProperty AlwaysIncludedShaders
        {
            get
            {
                var serializedProperty = AlwaysIncludedShadersEditor.serializedObject.FindProperty("m_AlwaysIncludedShaders");
                return serializedProperty;
            }
        }

        private static Editor AlwaysIncludedShadersEditor
        {
            get
            {
                Editor.CreateCachedEditor(GraphicsSettings, mAlwaysIncludedShadersEditorType, ref mAlwaysIncludedShadersEditor);
                return mAlwaysIncludedShadersEditor;
            }
        }

        private static Object GraphicsSettings
        {
            get
            {
                var type = typeof (GraphicsSettings);
                var method = type.GetMethod("GetGraphicsSettings", BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic);
                var ret = (Object) method.Invoke(null, null);
                return ret;
            }
        }

        #endregion
    }
}